package com.example.layui_project.controller;

import com.example.layui_project.dto.JsonData;
import com.example.layui_project.entity.SysUser;
import com.example.layui_project.enums.ResultCode;
import com.example.layui_project.service.UserService;
import com.example.layui_project.utils.BestUitls;
import com.example.layui_project.utils.MD5Util;
import com.google.code.kaptcha.Producer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
@RestController
@RequestMapping("login")
public class LoginController {
    //注入
    @Autowired
    private Producer producer;
    @Autowired
    private UserService userService;

    /**
     * 生成验证码
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws Exception
     */
    @GetMapping("defaultKaptcha.do")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到session中
            String createText = producer.createText();
            httpServletRequest.getSession().setAttribute("vrifyCode", createText);
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = producer.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream =
                httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    /**
     * 判断该用户是否存在
     * @param user
     * @param session
     */
    @PostMapping("startLogin.do")
    public JsonData startLogin(@RequestBody SysUser user, HttpSession session){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(), MD5Util.md5to32string(user.getPassword()));
        try {
            // 获取verifyCode
            String verifyCode = (String) session.getAttribute("vrifyCode");
            if(!user.getVerifyCode().equals(verifyCode)){
                return JsonData.fail(ResultCode.VERIFYCODE_ERROR.getCode(),ResultCode.VERIFYCODE_ERROR.getInfo());
            }
            subject.login(usernamePasswordToken);
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            // 当用户名或者验证码输入错误会捕获异常(IncorrectCredentialsException)该异常代表用户名或者密码错误
            return JsonData.fail(ResultCode.USERINFO_ERROR.getCode(),ResultCode.USERINFO_ERROR.getInfo());
        }
        return JsonData.success();
    }
    /*@PostMapping("startLogin.do")
    public JsonData loginDo(@RequestBody SysUser user, HttpSession session){
        try {
            // 获取verifyCode
            String verifyCode = (String) session.getAttribute("vrifyCode");
            if(BestUitls.isNotBlank(user)){
                // 首先判断验证码是否正确
                if(!user.getVerifyCode().equals(verifyCode)){
                    return JsonData.fail(ResultCode.VERIFYCODE_ERROR.getCode(),ResultCode.VERIFYCODE_ERROR.getInfo());
                }
                boolean exist = userService.isExist(user);
                if (!exist){
                    return JsonData.fail(ResultCode.USERINFO_ERROR.getCode(),ResultCode.USERINFO_ERROR.getInfo());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return  JsonData.fail(ResultCode.SYSTEM_BUSY.getCode(),ResultCode.SYSTEM_BUSY.getInfo());
        }
        return JsonData.success();
    }*/
}
